import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_turbolink_attribution/flutter_turbolink_attribution.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/utils/storage/LSUtil.dart';

import 'common_utils/log_util.dart';

const String projectID = 'd23dgs9rogtlpvf24vag';
const String appKey = 'a1a98bc49ed0359353a8d6c558b8c281';
const String appSecret = 'ad9a8e941ddb0728870bf115a4e5e7b8d462aebf';

class TurbolinkUtils {
  static Future<void> init() async {
    if (kDebugMode) {
      TurbolinkSdk.enableLogger();
    }
    TurbolinkSdk.withEventCallback((args) {
      LogUtil.e('智链返回数据-${args.linkData}');
      String code = args.linkData['code'] ?? "";
      if (code.isNotEmpty) {
        // 判断code是否有效
        ResourceApis.validateInviteCode(code).then((value) {
          if (value.isSuccess && value.data == true) {
            LSUtil.saveInviteCode(code, true);
          } else {
            LSUtil.saveInviteCode(code, false);
          }
        });
      }
    });
    TurbolinkSdk.setLaunchCampaignDelay(-1);
    TurbolinkSdk.autoInstance(
      projectID,
      appKey,
      appSecret,
    );
    TurbolinkSdk.withEventListenerCallback((args) {
      LogUtil.e("TurboLinkSDK, withEventListenerCallback:${args.arguments}:${args.scheme}:${args.campaignUrl}:${args.additionalParam}");
    });
    TurbolinkSdk.withPointListenerCallback((args) {
      LogUtil.e("TurboLinkSDK, withPointListenerCallback: ${args.campaignTitle}:${args.campaignLang}:${args.campaignUrl}:${args.user}:${args.position}");
    });
    TurbolinkSdk.withRedirectListenerCallback((args) {
      LogUtil.e("TurboLinkSDK, withRedirectListenerCallback: ${args.campaignId}_${args.campaignTitle}_${args.campaignLang}_${args.campaignUrl}_${args.user}_${args.type}_${args.appUrl}_${args.rewardTitle}_${args.kvData.values}");
    });
  }

  ///链接判断
  static bool check(String link) {
    return TurbolinkSdk.isUrlBelongTurboLink(link);
  }

  ///链接解析
  static void resolve(String link) {
    LogUtil.e('智链codeSearch--${link}');
    TurbolinkSdk.codeSearch(link);
  }

  ///检查剪切板数据
  static void checkClipboard() {
    Clipboard.getData(Clipboard.kTextPlain).then((value) {
      if (value != null) {
        LogUtil.e('剪切板数据--${value.text}');
        String text = value.text ?? "";
        if (check(text)) {
          resolve(text);
        }
      }
    });
  }
}
